package com.ruoyi.project.ledger.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.ledger.domain.LedgerManagementRegistration;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerBusinessRegistration;
import com.ruoyi.project.ledger.service.ILedgerBusinessRegistrationService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 进驻经营业户登记台账Controller
 *
 * @author ruoyi
 * @date 2020-04-14
 */
@RestController
@RequestMapping("/ledger/business")
public class LedgerBusinessRegistrationController extends BaseController
{
    @Autowired
    private ILedgerBusinessRegistrationService ledgerBusinessRegistrationService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询进驻经营业户登记台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:business:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerBusinessRegistration ledgerBusinessRegistration)
    {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerBusinessRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerBusinessRegistration.setAreas(areas);
        ledgerBusinessRegistration.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerBusinessRegistration> list = ledgerBusinessRegistrationService.selectLedgerBusinessRegistrationList(ledgerBusinessRegistration);
        return getDataTable(list);
    }

    /**
     * 导出进驻经营业户登记台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:business:export')")
    @Log(title = "进驻经营业户登记台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerBusinessRegistration ledgerBusinessRegistration)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerBusinessRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerBusinessRegistration.setAreas(areas);
        ledgerBusinessRegistration.setManagementCharacters(managementCharacters);
        List<LedgerBusinessRegistration> list = ledgerBusinessRegistrationService.selectLedgerBusinessRegistrationList(ledgerBusinessRegistration);
        for (LedgerBusinessRegistration registration : list){
            registration.setDate(new SimpleDateFormat("yyyy-MM-dd").format(registration.getEnteringDate()));
        }

        String tplPath =this.getClass().getResource("/").getPath() +"excel/进驻经营业户登记台账.xls";
        String fileName = "进驻经营业户登记台账.xls";

        //fileName = FileUtils.setFileDownloadHeader(request, fileName);

        Map<String, List<LedgerBusinessRegistration>> beanParams = new HashMap<String, List<LedgerBusinessRegistration>>();
        beanParams.put("list", list);

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        OutputStream out = null;
        Workbook workbook = null;
        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            workbook = former.transformXLS(in, beanParams);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(fileName));
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null)
            {
                try
                {
                    workbook.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return AjaxResult.error("导出失败");
    }

    /**
     * 获取进驻经营业户登记台账详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerBusinessRegistrationService.selectLedgerBusinessRegistrationById(id));
    }

    /**
     * 新增进驻经营业户登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:business:add')")
    @Log(title = "进驻经营业户登记台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerBusinessRegistration ledgerBusinessRegistration)
    {
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long stationId = user.getStationId();
            ledgerBusinessRegistration.setStationId(stationId);
            ledgerBusinessRegistration.setCreateId(String.valueOf(user.getUserId()));
        }
        else{
            return AjaxResult.error("当前角色无新增权限");
        }
        return toAjax(ledgerBusinessRegistrationService.insertLedgerBusinessRegistration(ledgerBusinessRegistration));
    }

    /**
     * 修改进驻经营业户登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:business:edit')")
    @Log(title = "进驻经营业户登记台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerBusinessRegistration ledgerBusinessRegistration)
    {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            Long stationId = user.getStationId();
            ledgerBusinessRegistration.setStationId(stationId);
            ledgerBusinessRegistration.setUpdateId(String.valueOf(user.getUserId()));
        }else{
            return AjaxResult.error("当前角色无修改权限");
        }
        return toAjax(ledgerBusinessRegistrationService.updateLedgerBusinessRegistration(ledgerBusinessRegistration));
    }

    /**
     * 删除进驻经营业户登记台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:business:remove')")
    @Log(title = "进驻经营业户登记台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerBusinessRegistrationService.deleteLedgerBusinessRegistrationByIds(ids));
    }
}
